/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.excel.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.star.framework.excel.core.Column;
import cn.star.framework.excel.handler.settings.Link;
import cn.star.framework.excel.handler.settings.Link.AddressCalculate;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * 链接<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
public class CellLinkHandler implements CellWriteHandler, OrderHandler {
  private final Link setting;
  private final List<Column> columns;
  private Cell cell;

  public CellLinkHandler(Link setting, List<Column> columns) {
    // 参照：https://blog.csdn.net/wjg276633/article/details/131411101
    this.setting = setting;
    this.columns = columns;
  }

  @Override
  public void afterCellDispose(
      WriteSheetHolder writeSheetHolder,
      WriteTableHolder writeTableHolder,
      List<WriteCellData<?>> cellDataList,
      Cell cell,
      Head head,
      Integer relativeRowIndex,
      Boolean isHead) {

    if (isHead
        || setting == null
        || setting.getType() == null
        || CollectionUtil.isEmpty(setting.getLink())
        || CollectionUtil.isEmpty(head.getHeadNameList())) {
      return;
    }

    // 对于值为空的单元格来说，无需设置链接
    try {
      if (StrUtil.isBlank(cell.getStringCellValue())) {
        return;
      }
    } catch (Exception exception) {
      // 忽略异常，可能获取值会出现异常
    }

    if (String.join("", setting.getLink()).equals(String.join("", head.getHeadNameList()))) {
      Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
      CreationHelper helper = workbook.getCreationHelper();
      String address = setting.getAddress();
      if (StrUtil.isBlank(address)) {
        AddressCalculate calculate = setting.getCalculate();
        if (calculate != null) {
          address = calculate.calculate(columns, head, cell, false);
        }
      }
      if (StrUtil.isBlank(address)) {
        return;
      }
      Hyperlink hyperlink = helper.createHyperlink(setting.getType());
      hyperlink.setAddress(address);
      cell.setHyperlink(hyperlink);
      this.cell = cell;
    } else if (this.cell != null) {
      // 在设置样式的时候需要注意，若直接给当前的cell设置样式，则不生效，
      // 不生效的原因可能是内部实现的 CellStyleHandler 最后统一做了样式调整导致的；但是经过验证并不是这个可能性；
      // 故此需要记录上一次的 cell 在此处进行设置样式
      Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
      CellStyle style = this.getDefaultLinkCellStyle(workbook);
      this.cell.setCellStyle(style);
    }
  }

  private CellStyle getDefaultLinkCellStyle(Workbook workbook) {
    CellStyle style = workbook.createCellStyle();

    Font font = workbook.createFont();
    font.setFontName("宋体");
    font.setUnderline(Font.U_SINGLE);
    font.setBold(true);
    font.setColor(IndexedColors.BLUE.getIndex());
    font.setFontHeightInPoints((short) 10);

    style.setFont(font);
    style.setBorderBottom(BorderStyle.DASHED);
    style.setBorderTop(BorderStyle.DASHED);
    style.setBorderLeft(BorderStyle.DASHED);
    style.setBorderRight(BorderStyle.DASHED);

    return style;
  }

  @Override
  public int order() {
    return this.wrapper(OrderStrategyType.CELL_LINK);
  }
}
